// @ts-ignore
import {fetch as fetchPolyfill} from "whatwg-fetch"
import transformUtils from "./transformUtils";
import {message} from "antd";
import host from '../config/host'

interface Api {
    url: string
    method: string
}
async function request(
    api: Api,
    params?: any,
    headers: Map<string, string> = new Map<string, string>()
    ) {
    let url = host+api.url
    const method = api.method.toUpperCase()
    const token = localStorage.getItem("token")
    if (token) {
        headers.set("token", token)
    }
    let opts: any
    if (method === 'GET') {
        headers.set('Content-Type', 'application/x-www-form-urlencoded')
        opts = {
            method: method,
            credentials: 'include',
            headers: transformUtils.strMapToObj(headers)
        }
        if (params) {
            url += "?"
            const ks = Object.keys(params)
            ks.forEach((k: string)=>{
                if (params[k] !== '' && params[k] !== undefined && params[k] !== null) {
                    url += `${k}=${params[k]}&`
                }
            })
        }
    } else if (method === 'POST') {
        headers.set('Content-Type', 'application/json')
        opts = {
            method: method,
            credentials: 'include',
            headers: transformUtils.strMapToObj(headers),
            body: params?JSON.stringify(params):undefined
        }
    } else {
        return undefined
    }
    const res = await fetchPolyfill(url, opts)
    let data = null
    let resp: any
    try {
        resp = await res.json()
    } catch (e) {
        return data
    }
    if (resp && resp.token) {
        localStorage.setItem("token", resp.token)
    }
    if (resp.code === 200) {
        data = resp.data
    }else{
        message.error(resp.tip || '未知错误', 3)
    }
    return data
}

export default request